<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    @cancel="onButtonCancelClick"
  >
    <BasicTree
      v-if="treeData.length"
      title="人员列表"
      toolbar
      search
      :height="300"
      ref="treeRef"
      :clickRowToExpand="false"
      :checkable="true"
      :treeData="treeData"
      :checkedKeys="checkedKeys"
      :showLine="{ showLeafIcon: false }"
      :defaultExpandAll="true"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, inject, unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { BasicTree, TreeItem, TreeActionType } from '/@/components/Tree';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { getEduRecordUsers, setEduRecordUsers } from '/@/api/ehs/eduRecord';

  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetEduRecordUser',
    components: {
      BasicTree,
      BasicModal,
    },
    setup(_, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const treeRef = ref<Nullable<TreeActionType>>(null);
      function getTree() {
        const tree = unref(treeRef);
        if (!tree) {
          throw new Error('tree is null!');
        }
        return tree;
      }

      const dataId = ref('');
      const orgcode = ref('');
      const treeData = ref<TreeItem[]>([]);

      //已经关联的key
      const checkedKeys = ref<number[] | string[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
            orgcode.value = unrefData.orgcode;
          }
        }
        setModalProps({ confirmLoading: false });
        checkedKeys.value = [];
        getUserList();
      });

      /**
       * 获取树形结构数据
       */
      async function getUserList() {
        await getEduRecordUsers(dataId.value)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            treeData.value = res.map((item) => {
              return {
                title: item.name,
                key: item.id,
                children: item.children,
              };
            });
            checkedKeys.value = res.map((item) => {
              if (item.checked) return item.id;
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，调用接口保存关联信息
       */
      async function onButtonOkClick() {
        //获取勾选的节点
        const keys = getTree().getCheckedKeys();
        console.log('获取勾选的key', keys);
        try {
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          setEduRecordUsers({ eduid: dataId.value, uids: keys })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('设置成功', 2);
              }
              closeModal();
              emit('success');
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } finally {
          setModalProps({ confirmLoading: false });
        }
        // 清空选中的行;
        checkedKeys.value = [];
        //清空搜索框的值
        getTree().setSearchValue('');
      }

      /**
       * 点击取消按钮
       */
      function onButtonCancelClick() {
        //清空搜索框的值
        getTree().setSearchValue('');
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      return {
        registerModal,
        getUserList,
        onButtonOkClick,
        onButtonCancelClick,
        treeData,
        checkedKeys,
        treeRef,
        displayModuleTitle,
      };
    },
  });
</script>
